package com.dongdongsongcan.app.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dongdongsongcan.app.R;
import com.dongdongsongcan.app.common.DDConstant;
import com.dongdongsongcan.app.common.DDMessageDef;
import com.dongdongsongcan.app.common.DDSpKeysDef;
import com.dongdongsongcan.app.control.AddressControl;
import com.dongdongsongcan.app.control.OrderControl;
import com.dongdongsongcan.app.control.ShoppingCarControl;
import com.dongdongsongcan.app.control.UserControl;
import com.dongdongsongcan.app.control.bean.AddressData;
import com.dongdongsongcan.app.control.bean.DeliverPriceData;
import com.dongdongsongcan.app.control.bean.OrderSubmitData;
import com.dongdongsongcan.app.control.bean.ShopData;
import com.dongdongsongcan.app.control.bean.UserFavorableData;
import com.dongdongsongcan.app.db.ShoppingCarDao;
import com.dongdongsongcan.app.db.bean.ShoppingCarDBBean;
import com.dongdongsongcan.app.view.OrderInfoFoodItem;
import com.prone.vyuan.widget.dpdialog.CustomDialog;
import com.su.dolphin.control.bean.BaseBean;
import com.su.dolphin.control.task.CtrlTask;
import com.su.dolphin.core.notification.DpMessageCenter;
import com.su.dolphin.utils.DataStoreUtil;
import com.su.dolphin.utils.TimeUtil;
import com.su.dolphin.utils.mgr.DpActivityManager;
import com.su.dolphin.utils.ui.TipsUtil;
import com.su.dolphin.view.activity.BaseActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class SubmitOrderActivity extends BaseActivity {

    private LinearLayout mSubmitorder_ll_foodlist;
    private ShopData.Shop mShop;
    private TextView mSubmit_order_user;
    private TextView msubmit_order_address;
    private View mSubmit_order_edit_address;
    private RadioGroup mSubmit_order_paymethod;
    private TextView mSubmit_order_deliverytime;
    private EditText mSubmit_order_note;
    private TextView mSubmit_order_score;
    private TextView mSubmit_order_delivery_cost;
    private TextView mSubmit_order_total_price;
    private TextView mSubmit_order_favourable;
    private TextView mSubmit_order_equation;
    private TextView mSubmit_order_shouldpay;
    private TextView mSubmit_order_submit;
    private TextView mSubmit_order_shopname;
    private AddressData.Address mAddress;
    private double mFavorable;
    private double mDeliverPrice;
    private double mTotalPrice;
    private List<ShoppingCarDBBean> mShoppingCarDBBeans;
    private Dialog mProgressDialog;

    public static void startFrom(Context context, ShopData.Shop shop) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("shop", shop);
        DpActivityManager.i().startActivity(context, SubmitOrderActivity.class,
                bundle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        register(DDMessageDef.N_SUBMIT_ORDER_CHOOSADDRESS);
        mShop = (ShopData.Shop) this.getIntent().getExtras()
                .getSerializable("shop");
        setContentView(R.layout.activity_submit_order);
        getDpTitleBar().setTitle("提交订单");
    }

    @Override
    public void initView() {
        mSubmitorder_ll_foodlist = (LinearLayout) findViewById(R.id.submit_order_ll_foodlist);
        mSubmit_order_user = (TextView) findViewById(R.id.submit_order_user);
        msubmit_order_address = (TextView) findViewById(R.id.submit_order_address);
        mSubmit_order_edit_address = findViewById(R.id.submit_order_edit_address);
        mSubmit_order_paymethod = (RadioGroup) findViewById(R.id.submit_order_paymethod);
        mSubmit_order_deliverytime = (TextView) findViewById(R.id.submit_order_deliverytime);
        mSubmit_order_note = (EditText) findViewById(R.id.submit_order_note);
        mSubmit_order_score = (TextView) findViewById(R.id.submit_order_score);
        mSubmit_order_delivery_cost = (TextView) findViewById(R.id.submit_order_delivery_cost);
        mSubmit_order_total_price = (TextView) findViewById(R.id.submit_order_total_price);
        mSubmit_order_favourable = (TextView) findViewById(R.id.submit_order_favourable);
        mSubmit_order_equation = (TextView) findViewById(R.id.submit_order_equation);
        mSubmit_order_shouldpay = (TextView) findViewById(R.id.submit_order_shouldpay);
        mSubmit_order_submit = (TextView) findViewById(R.id.submit_order_submit);
        mSubmit_order_shopname = (TextView) findViewById(R.id.submit_order_shopname);
        mProgressDialog = TipsUtil.buildDPProgressDialog(SubmitOrderActivity.this, "正在提交,请稍后...");
        mProgressDialog.setCancelable(false);
    }

    @Override
    public void setListener() {
        mSubmit_order_edit_address
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AddressListActivity.startFrom(SubmitOrderActivity.this,
                                AddressListActivity.MODE_CHOOSE);
                    }
                });
        // {
        // "token": "e00cf25ad42683b3df678c61f42c6bda",
        // "user_name": "admin",
        // "order_louhao1": "\u697c\u53f7",
        // "order_name": "\u59d3\u540d",
        // "order_sex": "\u7537",
        // "order_mobile": "135865478547",
        // "order_arrive": "\u5c3d\u5feb\u9001\u5230",
        // "order_beta": "\u5907\u6ce8",
        // "order_shop_id": "19812",
        // "order_pay_method": "afterpayment",
        // "order_area_id": "163",
        // "order_foods": [{
        // "id": 1,
        // "deliver_price": 3,
        // "count": 3,
        // "make": 0,
        // "price": 139,
        // "proudctid": 3469,
        // "proudctname":
        // "\u6e2f\u5f0f\u6df1\u4e95\u70e7\u9e45\uff08\u534a\u53ea\uff09",
        // "shopid": "132",
        // "weight": "0"
        // }]
        // }
        mSubmit_order_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserControl.i().userExist()) {
                    LoginActivity.startFrom(SubmitOrderActivity.this);
                    TipsUtil.toast("请先登陆");
                    return;
                }
                if (mAddress == null) {
                    TipsUtil.toast("请先选择地址");
                    return;
                }
                OrderSubmitData orderSubmitData = new OrderSubmitData();
                String order_pay_method = null;

                switch (mSubmit_order_paymethod.getCheckedRadioButtonId()) {
                    case R.id.submit_order_paymethod_alipay:
                        order_pay_method = "submit_order_paymethod_alipay";
                        break;
                    case R.id.submit_order_paymethod_pos:
                        order_pay_method = "onlinepayment";
                        break;
                    case R.id.submit_order_paymethod_cod:
                        order_pay_method = "afterpayment";
                        break;
                }
                // afterpayment
                // onlinepayment
                // orderSubmitData.setOrder_area_id(mAddress.getInfo_id() + "");
                orderSubmitData.setOrder_area_id(mAddress.getInfo_area_id()
                        + "");
                orderSubmitData.setOrder_louhao1(mAddress.getInfo_louhao1());
                orderSubmitData.setOrder_mobile(mAddress.getInfo_mobile());
                orderSubmitData.setOrder_name(mAddress.getInfo_name());
                orderSubmitData.setOrder_beta(mSubmit_order_note.getText()
                        .toString());
                orderSubmitData.setOrder_pay_method(order_pay_method);
                orderSubmitData.setOrder_arrive(mSubmit_order_deliverytime
                        .getText().toString());
                orderSubmitData.setOrder_shop_id(mShop.getShop_id() + "");
                orderSubmitData.setOrder_sex(mAddress.getInfo_sex());
                orderSubmitData.setOrder_foods(mShoppingCarDBBeans);
                mProgressDialog.show();
                OrderControl.submitOrder(orderSubmitData,
                        new CtrlTask.IControlResponse<BaseBean>() {
                            @Override
                            public void onControlResponse(BaseBean data) {
                                TipsUtil.toast(data.getMsg());
                                mProgressDialog.dismiss();
                                if (data.isOk()) {
                                    ShoppingCarDao.clearShopingCar(mShop
                                            .getShop_id());// 清空这个购物车
                                    DpMessageCenter
                                            .i()
                                            .notify(DDMessageDef.N_SUBMIT_ORDER_SUCCESS);
                                    finish();
                                }
                            }
                        });

            }
        });
        mSubmit_order_deliverytime
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        chooseTime();
                    }
                });
    }

    private void chooseTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        List<String> times = new ArrayList<>();
        times.add("立即送达");

        List<String> tmp = new ArrayList<>();
        String hourStr = "";
        if (minute > 30) {
            hour++;
            tmp.add(hour + ":00");
            for (int i = 0; i < 4; i++) {
                if (hour > 23) {
                    hourStr = "次日" + (hour - 24) + "";
                } else {
                    hourStr = hour + "";
                }
                tmp.add(hourStr + ":30");
                hour++;
                if (hour > 23) {
                    hourStr = "次日" + (hour - 24) + "";
                } else {
                    hourStr = hour + "";
                }
                tmp.add(hourStr + ":00");
            }

        } else {
            tmp.add(hour + ":30");
            for (int i = 0; i < 4; i++) {
                if (hour > 23) {
                    hourStr = "次日" + (hour - 24) + "";
                } else {
                    hourStr = hour + "";
                }
                tmp.add(hourStr + ":00");
                hour++;
                if (hour > 23) {
                    hourStr = "次日" + (hour - 24) + "";
                } else {
                    hourStr = hour + "";
                }
                tmp.add(hourStr + ":30");
            }
        }
        int i = 0;
        while (i < tmp.size() - 1) {
            times.add(tmp.get(i) + "-" + tmp.get(i + 1));
            i += 2;
        }

        final String[] timesInArray = times.toArray(new String[times.size()]);
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("选择送货时间")
                .setSingleChoiceItems(timesInArray, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                TipsUtil.toast(timesInArray[which]);
                                mSubmit_order_deliverytime
                                        .setText(timesInArray[which]);
                            }
                        }).create().show();

    }

    @Override
    public void initData() {
        setAddressInfo();
        mSubmit_order_shopname.setText(mShop.getShop_name());
        mShoppingCarDBBeans = ShoppingCarControl.i().getShoppingCarList(
                mShop.getShop_id());
        for (ShoppingCarDBBean shoppingCarDBBean : mShoppingCarDBBeans) {
            OrderInfoFoodItem orderInfoFoodItem = new OrderInfoFoodItem(this);
            orderInfoFoodItem.setInfo(shoppingCarDBBean);
            mSubmitorder_ll_foodlist.addView(orderInfoFoodItem.getView());
        }
        getFavourable();
    }

    private void getFavourable() {
        UserControl.i().user_favorable(mShop.getShop_id(),
                new CtrlTask.IControlResponse<UserFavorableData>() {
                    @Override
                    public void onControlResponse(UserFavorableData data) {
                        if (data.isOk()) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = 0; i < data.getResult().size(); i++) {
                                stringBuilder.append(
                                        data.getResult().get(i).getText())
                                        .append("\n");
                                mFavorable += data.getResult().get(i)
                                        .getFavorable();
                            }
                            String favourabe = stringBuilder.substring(0,
                                    stringBuilder.length() - 1);
                            mSubmit_order_favourable.setText(favourabe);
                        }
                        getDeliverPrice();
                    }
                });

    }

    private void getDeliverPrice() {
        if (mAddress != null) {
            AddressControl.i().distance_price(mAddress.getInfo_area_id(),
                    mShop.getShop_id(),
                    new CtrlTask.IControlResponse<DeliverPriceData>() {
                        @Override
                        public void onControlResponse(DeliverPriceData data) {
                            if (data.isOk()) {
                                mSubmit_order_delivery_cost
                                        .setText(DDConstant.RMB
                                                + data.getResult());
                                mDeliverPrice = data.getResult();
                                refreshTotalPrice();
                            }
                        }
                    });
        } else {
            refreshTotalPrice();
        }
    }

    private void refreshTotalPrice() {
        mTotalPrice = mDeliverPrice;
        for (int i = 0; i < mShoppingCarDBBeans.size(); i++) {
            mTotalPrice += mShoppingCarDBBeans.get(i).getPrice()
                    * mShoppingCarDBBeans.get(i).getCount();
            mTotalPrice += mShoppingCarDBBeans.get(i).getPackage_price()
                    * mShoppingCarDBBeans.get(i).getCount();
        }
        mSubmit_order_total_price.setText("订单总计: " + DDConstant.RMB
                + mTotalPrice);
        String result1 = "商品金额:" + DDConstant.RMB + mTotalPrice;
        if (mFavorable > 0) {
            result1 += "-优惠:" + DDConstant.RMB + mFavorable;
        }
        mSubmit_order_equation.setText(result1);
        mSubmit_order_shouldpay.setText("还需支付:" + DDConstant.RMB
                + (mTotalPrice - mFavorable));
    }

    @Override
    public void onNotify(DpMessageCenter.MCMessage notification) {
        if (notification.notificationID == DDMessageDef.N_SUBMIT_ORDER_CHOOSADDRESS) {
            mAddress = (AddressData.Address) notification.extObj;
            setAddressInfo();
            DataStoreUtil.i().putString(DDSpKeysDef.KEY_DEFAULT_ADDRESS,
                    JSON.toJSONString(mAddress));
        }
    }

    private void setAddressInfo() {
        if (UserControl.i().getDefaultAddress() != null) {
            mAddress = UserControl.i().getDefaultAddress();
            msubmit_order_address.setText(mAddress.getInfo_area()
                    + mAddress.getInfo_louhao1());
            mSubmit_order_user.setText(mAddress.getInfo_name() + "  "
                    + mAddress.getInfo_sex() + "" + mAddress.getInfo_mobile());
            getDeliverPrice();
        }
    }
}
